package com.lap.generator.domain.template.strategy;

import com.lap.generator.application.assembler.ModelTransformer;
import com.lap.generator.commons.exception.GeneratorException;
import com.lap.generator.commons.tools.FileUtil;
import com.lap.generator.commons.tools.PackageUtil;
import com.lap.generator.domain.CoreFile;
import com.lap.generator.domain.TemplateModel;
import com.lap.generator.domain.template.CodeGenContext;
import com.lap.generator.domain.template.CodeTemplate;
import com.lap.generator.domain.valueobject.CodeType;
import com.lap.generator.infrastructure.persistence.TemplateEngine;
import freemarker.template.TemplateException;
import java.io.IOException;
import java.util.List;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class QueryDtoGen implements CodeTemplate<CoreFile> {
  
  @Override
  public CodeType getType() {
    return CodeType.DRIVING;
  }

  @Override
  public List<CoreFile> generate(CodeGenContext context) {
    TemplateModel model = ModelTransformer.transform(context.tableMeta(), context.envConfig());
    try {
      TemplateEngine engine = new TemplateEngine();
      String dtoContent = engine.processTemplate("application/QueryDto.java.ftl", model);
      String dtoPackName =
          PackageUtil.pack2Path(model.getBasePackage(), "application", model.getModule(), "dto");
      String dtoFileName = FileUtil.resolverFile("java", model.getClassName(), "Dto");
      CoreFile dtoFile =
          CoreFile.builder()
          .path(dtoPackName)
          .fileName(dtoFileName)
          .content(dtoContent)
          .build();

      String conditionContent =
          engine.processTemplate("application/QueryCondition.java.ftl", model);
      String fileName = FileUtil.resolverFileName(model.getClassName(), "Query", "PageQuery");
      String conditionPackName =
          PackageUtil.pack2Path(model.getBasePackage(), "application", model.getModule(), "dto");
      String conditionFileName = FileUtil.resolverFile("java", fileName);
      CoreFile conditionFile = 
          CoreFile.builder()
          .path(conditionPackName)
          .fileName(conditionFileName)
          .content(conditionContent)
          .build();

      return List.of(dtoFile, conditionFile);
    } catch (IOException | TemplateException e) {
      throw new GeneratorException("QueryDto engine error:", e);
    }
  }
}
